import styles from './EditHeader.module.scss'
import {Button, Input, message, Space, Typography} from "antd";
import {EditOutlined, LeftOutlined, LoadingOutlined} from "@ant-design/icons";
import {useNavigate, useParams} from "react-router-dom";
import {EditToolbar} from "./EditToolbar";
import useGetPageInfo from "../../../hooks/useGetPageInfo";
import {changePageTitle} from "../../../store/pageInfoReducer";
import {ChangeEvent, useEffect, useState} from "react";
import {useDispatch} from "react-redux";
import useGetComponentInfo from "../../../hooks/useGetComponentInfo";
import {useDebounceEffect, useKeyPress, useRequest} from "ahooks";
import {updateQuestionService} from "../../../services/question";

const {Title} = Typography;

const SaveButton = () => {
    const {id} = useParams()
    const {componentList = []} = useGetComponentInfo();
    const pageInfo = useGetPageInfo()
    const {loading, run: save} = useRequest(async () => {
        if (!id) return
        await updateQuestionService(id, {componentList, ...pageInfo})
    }, {
        manual: true
    })
    useKeyPress(['ctrl.s', 'meta.s'], (event: KeyboardEvent) => {
        event.preventDefault()
        if (!loading) save()
    })
    useDebounceEffect(() => {
        save()
    }, [componentList, pageInfo], {
        wait: 1000
    });
    return <Button onClick={save} disabled={loading} icon={loading ? <LoadingOutlined/> : null}>保存</Button>
}

const PublishButton = () => {
    const nav = useNavigate()
    const {id} = useParams()
    const {componentList = []} = useGetComponentInfo();
    const pageInfo = useGetPageInfo()
    const {loading, run: pub} = useRequest(async () => {
        if (!id) return
        await updateQuestionService(id, {componentList, ...pageInfo, isPublished: true})
    }, {
        manual: true,
        onSuccess() {
            message.success('发布成功').then(r => '')
            nav(`/question/stat/${id}`)
        }
    })

    return <Button onClick={pub} disabled={loading} type={'primary'}>发布</Button>
}
const TitleElem = () => {
    const dispatch = useDispatch()
    const {title} = useGetPageInfo()
    const [editState, setEditState] = useState(false)

    function handleChange(event: ChangeEvent<HTMLInputElement>) {
        const newTitle = event.target.value.trim()
        if (!newTitle) return
        dispatch(changePageTitle(newTitle))
    }

    if (editState) return <Input value={title} onPressEnter={() => setEditState(false)}
                                 onBlur={() => setEditState(false)} onChange={handleChange}></Input>
    return (
        <Space>
            <Title>{title}</Title>
            <Button shape={'circle'} type={'text'} icon={<EditOutlined/>} onClick={() => setEditState(true)}></Button>
        </Space>)
}
export const EditHeader = () => {
    const nav = useNavigate()
    return (
        <div className={styles['header-wrapper']}>
            <div className={styles.header}>
                <div className={styles.left}>
                    <Space>
                        <Button onClick={() => {
                            nav(-1)
                        }} type={'link'} icon={<LeftOutlined/>}>返回</Button>
                        <TitleElem></TitleElem>
                    </Space>
                </div>
                <div className={styles.main}>
                    <EditToolbar></EditToolbar>
                </div>
                <div className={styles.right}>
                    <Space>
                        <SaveButton></SaveButton>
                        <PublishButton/>
                    </Space>
                </div>
            </div>
        </div>
    );
};